package com.sola.serviceapi.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.codec.Utf8;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@RestController
public class TestController {
    @Value("${security.oauth2.resource.jwt.key-value}")
    private String SigningKey;

    @GetMapping("/test")
    public String test(){
        return "这是service-api";
    }

    @GetMapping("/userinfo")
    public Object user(){
        //获取安全上下问的中的authentication,SpringSecurity的安全上下文默认存放于threadlocal中
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //从authentication里面获取用户信息，里面又用户的用户名，权限等相关信息.
        //principal的类型需要根据实际情况判定，使用ACCESSS_TOKEN时是User对象
        // 使用JWT时是一个字符串（username），
        // 如果认证服务器自定义/user接口，也可能时map或者其他
        Object principal =authentication.getPrincipal();

        return principal;
    }
    @GetMapping("/tokeninfo")
    public Object analysisToken(HttpServletRequest request){
        //从请求头中获取token
        String token = request.getHeader("Authorization").replace("bearer ", "");
        //用SigningKey（密钥）对token 进行解码，获取主体Claims对象
        Claims claims = Jwts.parser().setSigningKey(SigningKey.getBytes(StandardCharsets.UTF_8)).parseClaimsJws(token).getBody();
        //根据key可以获取value
        Object sola = claims.get("writer");
        return  sola;
    }
    @GetMapping("/token")
    public Object oken(HttpServletRequest request){
        //获取token
        String token = request.getHeader("Authorization").replace("bearer ", "");
        return  token;
    }
}
